package com.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.commons.Constants;

import vo.User;

/**
 * Servlet Filter implementation class UserLoginFilter
 */
@WebFilter({ "*.do", "*.jsp" })
public class UserLoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public UserLoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hsr=(HttpServletRequest)request;
		String uri=hsr.getRequestURI();
		//判断当前请求的是否为login.jsp或login.do或validateCode.do（生成验证码）如果是则需要放行
		if(uri.indexOf("login.jsp")!=-1||uri.indexOf("login.do")!=-1||uri.indexOf("validateCode.do")!=-1) {
			chain.doFilter(request, response);
		}else {
			HttpSession session=hsr.getSession();
			User user=(User)session.getAttribute(Constants.USER_SESSION_KEY);
			if(user!=null) {
				chain.doFilter(request, response);
			}else {
				hsr.setAttribute(Constants.REQUEST_MSG, "必须要登录");
				hsr.getRequestDispatcher("login.jsp").forward(request, response);
			}
		}
		
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
